package com.hoshiicloud.goods.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hoshiicloud.auth.vo.TokenUsersVO;
import com.hoshiicloud.common.exception.ServiceException;
import com.hoshiicloud.common.query.OmnipotentParam;
import com.hoshiicloud.common.query.OmnipotentWrapper;
import com.hoshiicloud.common.rpc.Response;
import com.hoshiicloud.common.update.UpdateBatchParam;
import com.hoshiicloud.common.utils.BeanUtils;
import com.hoshiicloud.goods.entity.sku.ExtSku;
import com.hoshiicloud.goods.entity.spu.ExtSpu;
import com.hoshiicloud.goods.param.spu.ExtSpuAddParam;
import com.hoshiicloud.goods.param.spu.ExtSpuQueryParam;
import com.hoshiicloud.goods.param.spu.ExtSpuUpdateParam;
import com.hoshiicloud.goods.service.ExtSpuService;
import com.hoshiicloud.goods.utils.UserInfoUtil;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 扩展SPU 控制器
 * </p>
 *
 * @author zhangshuhu
 * @since 2019-06-04
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/goods/ext-spu")
@Api(value = "扩展SPU", tags = {"扩展SPU"})
public class ExtSpuController {
    @Autowired
    private ExtSpuService extSpuService;

    /**
     * @param param
     * @return com.hoshiicloud.common.rpc.Response
     * @description: 分页查询扩展SPU
     */
    @ApiOperation(value = "分页查询扩展SPU")
    @PostMapping("/query/page")
    public Response<IPage<ExtSpu>> page(@RequestBody @Valid ExtSpuQueryParam param) {
        try {
            log.info("分页查询扩展SPU");
            QueryWrapper<ExtSpu> queryWrapper = new QueryWrapper<ExtSpu>();
            queryWrapper.lambda().eq(StringUtils.isNotBlank(param.getSpuId()), ExtSpu::getSpuId, param.getSpuId())
                           .eq(null != param.getCompanyId(), ExtSpu::getCompanyId, param.getCompanyId())
                           .eq(null != param.getPlatformId(), ExtSpu::getPlatformId, param.getPlatformId())
                           .eq(null != param.getStoreId(),ExtSpu::getStoreId,param.getStoreId())
                           .eq(StringUtils.isNotBlank(param.getSpuVideo()), ExtSpu::getSpuVideo, param.getSpuVideo())
                           .eq(StringUtils.isNotBlank(param.getSpuDescription()), ExtSpu::getSpuDescription, param.getSpuDescription())
                           .eq(StringUtils.isNotBlank(param.getTitle()), ExtSpu::getTitle, param.getTitle())
                           .eq(StringUtils.isNotBlank(param.getSpuImage()), ExtSpu::getSpuImage, param.getSpuImage())
                           .eq(param.getIsInvoice() != null, ExtSpu::getIsInvoice,param.getIsInvoice())
                           .eq(StringUtils.isNotBlank(param.getServiceDescription()), ExtSpu::getServiceDescription, param.getServiceDescription())
                           .eq(StringUtils.isNotBlank(param.getExtendProperty()), ExtSpu::getExtendProperty, param.getExtendProperty())
                           .eq(StringUtils.isNotBlank(param.getExtendSpec()), ExtSpu::getExtendSpec, param.getExtendSpec())
                           .eq(StringUtils.isNotBlank(param.getNotice()), ExtSpu::getNotice, param.getNotice())
                           .eq(param.getUpTime() != null, ExtSpu::getUpTime, param.getUpTime())
                           .eq(param.getDownTime() != null, ExtSpu::getDownTime, param.getDownTime())
                           .eq(param.getStatus() != null, ExtSpu::getStatus, param.getStatus())
                           .eq(param.getDeleted() != null, ExtSpu::getDeleted, param.getDeleted());
            IPage<ExtSpu> page = new Page<>(Long.parseLong(param.getPageNumber()), Long.parseLong(param.getPageSize()));
            String key = param.toString() + ",Page{pageNumber=" + param.getPageNumber() + ",pageSize=" + param.getPageSize() + "}";
            return Response.data(extSpuService.getPage(page, queryWrapper, key));
        } catch (Exception e) {
            log.error("分页查询扩展SPU异常", e);
            return Response.failed("分页查询扩展SPU异常");
        }
    }

    @ApiOperation(value = "分页查询扩展SPU带售价")
    @PostMapping("/query/list")
    public Response<IPage<Map<String, Object>>> getSpusWithMiniPrice(@RequestBody ExtSpuQueryParam param) {
        try {
            log.info("分页查询扩展SPU带售价");
            QueryWrapper<ExtSpu> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(StringUtils.isNotBlank(param.getSpuId()), "t.spu_id", param.getSpuId());
            queryWrapper.eq(StringUtils.isNotBlank(param.getSpuVideo()), "t.spu_video", param.getSpuVideo());
            queryWrapper.eq(StringUtils.isNotBlank(param.getSpuDescription()), "t.spu_description", param.getSpuDescription());
            queryWrapper.like(StringUtils.isNotBlank(param.getTitle()), "t.title", param.getTitle());
            queryWrapper.eq(StringUtils.isNotBlank(param.getSpuImage()), "t.spu_image", param.getSpuImage());
            queryWrapper.eq(null != param.getIsInvoice(), "t.is_invoice", param.getIsInvoice());
            queryWrapper.eq(StringUtils.isNotBlank(param.getServiceDescription()), "t.service_description", param.getServiceDescription());
            queryWrapper.eq(StringUtils.isNotBlank(param.getExtendProperty()), "t.extend_property", param.getExtendProperty());
            queryWrapper.eq(StringUtils.isNotBlank(param.getExtendSpec()), "t.extend_spec", param.getExtendSpec());
            queryWrapper.eq(StringUtils.isNotBlank(param.getNotice()), "t.notice", param.getNotice());
            queryWrapper.eq(null != param.getUpTime(), "t.up_time", param.getUpTime());
            queryWrapper.eq(null != param.getDownTime(), "t.down_time", param.getDownTime());
            // queryWrapper.eq(null != param.getCompanyId(), "t.companyid",param.getCompanyId());
            queryWrapper.eq(null != param.getPlatformId(), "t.platform_id", param.getPlatformId());
            queryWrapper.eq(null != param.getStoreId(), "t1.store_id", param.getStoreId());
            Page<Map<String, Object>> page = new Page<>(Long.parseLong(param.getPageNumber()), Long.parseLong(param.getPageSize()));
            String key = "ExtSpuQueryParam{"+param.toString() + "},Page{pageNumber=" + param.getPageNumber() + ",pageSize=" + param.getPageSize() + "}";

            return Response.data(extSpuService.getSpusWithMiniPrice(page, queryWrapper, key));
        } catch (Exception e) {
            log.error("分页查询扩展SPU带售价异常", e);
            return Response.failed("分页查询扩展SPU带售价异常");
        }
    }

    /**
     * 根据类目分页查询扩展SPU带售价
     * @param param 查询参数
     * @return Response<IPage<Map<String,Object>>>
     */
    @ApiOperation(value = "根据类目分页查询扩展SPU带售价")
    @PostMapping("/query/listCategoryId")
    public Response<IPage<Map<String,Object>>> getSpusByStoreIdAndCategoryId(@RequestBody ExtSpuQueryParam param) {
        try {
            log.info("根据类目分页查询扩展SPU带售价");
            QueryWrapper<ExtSpu> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(null != param.getPlatformId(), "t.platform_id",param.getPlatformId());
            queryWrapper.eq(null != param.getStoreId(), "t1.store_id",param.getStoreId());
            // queryWrapper.in(null != param.getCategoryId(), "t2.sales_category_id", 112,48,139,49,10,56,11,77,31,102,35,110,40,120,143,51,111,43,54,103);
            String key = param.getPlatformId()+":"+param.getStoreId()+":"+param.getCategoryId()+":"+param.getPageNumber()+":"+param.getPageSize();
            Page<Map<String,Object>> page = new Page<>(Long.parseLong(param.getPageNumber()), Long.parseLong(param.getPageSize()));
            queryWrapper.select(BeanUtils.getSqlSelect(ExtSpu.class));
            return Response.data(extSpuService.getSpusByStoreIdAndCategoryId(page, queryWrapper, key));
        } catch (ServiceException e) {
            return Response.failed(e.getError().getMsg());
        } catch (Exception e) {
            log.error("根据类目分页查询扩展SPU带售价异常", e);
            return Response.failed("根据类目分页查询扩展SPU带售价异常");
        }
    }

    /**
     * @param id
     * @return com.hoshiicloud.common.rpc.Response
     * @description: 根据id查询扩展SPU
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "根据id查询扩展SPU")
    @ApiParam(name = "id", value = "主键ID", required = true)
    public Response<ExtSpu> queryById(@PathVariable("id") Long id) {
        return Response.data(extSpuService.getById(id));
    }


    /**
     * @param
     * @return com.hoshiicloud.common.rpc.Response
     * @description: 根据店铺ID和spuId查询扩展SPU
     */
    @GetMapping("/getOneByStoreIdAndSpuId")
    @ApiOperation(value = "根据店铺ID和spuId查询扩展SPU")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "spuId", value = "spuId"),
            @ApiImplicitParam(name = "storeId", value = "店铺Id"),
    })
    public Response<ExtSpu> getOneByStoreIdAndSpuId(@RequestParam Map<String,Object> map) {
            QueryWrapper<ExtSpu> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(ExtSpu::getStoreId ,Long.valueOf(map.get("storeId").toString()))
            .eq( ExtSpu::getId ,Long.valueOf(map.get("spuId").toString()));
            return Response.data(extSpuService.getOne(queryWrapper)
        );
    }

    /**
     * @param param
     * @return com.hoshiicloud.common.rpc.Response
     * @description: 新增
     */
    @PostMapping("/save")
    @ApiOperation(value = "新增扩展SPU")
    public Response save(@RequestBody @Valid ExtSpuAddParam param) {

        // Bean数据转换
        ExtSpu entity;
        try {
            entity = BeanUtils.covertType(param, ExtSpu.class);
        } catch (Exception e) {
            log.error("Bean转换异常", e);
            return Response.failed("Bean转换异常");
        }
        boolean save = extSpuService.save(entity);
        return Response.data(save);
    }

    @PostMapping("/saveExtSpu")
    @ApiOperation(value = "新增分店扩展SPU")
    public Response<ExtSpu> saveExtSpu(@RequestBody @Valid ExtSpuAddParam param) {

        // Bean数据转换
        ExtSpu entity;
        try {
            entity = BeanUtils.covertType(param, ExtSpu.class);
        } catch (Exception e) {
            log.error("Bean转换异常", e);
            return Response.failed("Bean转换异常");
        }
        ExtSpu extSpu = extSpuService.saveExtSpu(entity);
        return Response.data(extSpu);
    }





    /**
     * @param param
     * @return com.hoshiicloud.common.rpc.Response
     * @description: 修改扩展SPU
     */
    @PutMapping("/update")
    @ApiOperation(value = "修改扩展SPU")
    public Response update(@RequestBody @Valid ExtSpuUpdateParam param) {

        // Bean数据转换
        ExtSpu entity;
        try {
            entity = BeanUtils.covertType(param, ExtSpu.class);
        } catch (Exception e) {
            log.error("Bean转换异常", e);
            return Response.failed("Bean转换异常");
        }
        return Response.data(extSpuService.updateById(entity));

    }

    /**
     * @param id
     * @return com.hoshiicloud.common.rpc.Response
     * @description: 删除扩展SPU
     */
    @DeleteMapping("/delete/{id}")
    @ApiOperation(value = "删除扩展SPU")
    @ApiParam(name = "id", value = "主键ID", required = true)
    public Response delete(@PathVariable("id") Long id) {
        return Response.data(extSpuService.deleteById(id));

    }

    /**
     * @Author:campchen
     * @Description: StringUtils.join(ids, " ") 为缓存中添加唯一KEY  如不合适可选择更好方法
     * @Date:上午 10:18 2019/5/11
     * @Param: ids
     * @return: com.hoshiicloud.common.rpc.Response
     */
    @ApiOperation(value = "根据id集合查询扩展SPU")
    @GetMapping("/getByIds")
    public Response getByIds(@RequestParam List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return Response.failed("id不能为空");
        }
        ids.sort(null);
        return Response.data(extSpuService.getByIds(ids, StringUtils.join(ids, "")));
    }

    /**
     * 获取SPU详情
     *
     * @param id 主键ID
     * @return Response<Map < String, Object>>
     */
    @GetMapping("/detail/{id}")
    @ApiOperation(value = "查询扩展SPU详情带售价标签类目")
    @ApiParam(name = "id", value = "主键ID", required = true)
    public Response<List<Map<String, Object>>> getSpuDetailWithOthers(@PathVariable("id") Long id) {
        return Response.data(extSpuService.getSpuDetailWithOthers(String.valueOf(id)));
    }

    /**
     * 获取缓存Key
     *
     * @param param 查询对象
     * @return String
     */
    private String getCacheKey(ExtSpuQueryParam param) {
        StringBuffer sb = new StringBuffer();
        if (null != param) {
            if (StringUtils.isNotBlank(param.getSpuId())) {
                sb.append(param.getSpuId()).append(":");
            }
            if (StringUtils.isNotBlank(param.getSpuVideo())) {
                sb.append(param.getSpuVideo()).append(":");
            }
            if (StringUtils.isNotBlank(param.getSpuDescription())) {
                sb.append(param.getSpuDescription()).append(":");
            }
            if (StringUtils.isNotBlank(param.getTitle())) {
                sb.append(param.getTitle()).append(":");
            }
            if (StringUtils.isNotBlank(param.getSpuImage())) {
                sb.append(param.getSpuImage()).append(":");
            }
            if (null != param.getIsInvoice()) {
                sb.append(param.getIsInvoice()).append(":");
            }
            if (StringUtils.isNotBlank(param.getServiceDescription())) {
                sb.append(param.getServiceDescription()).append(":");
            }
            if (StringUtils.isNotBlank(param.getExtendProperty())) {
                sb.append(param.getExtendProperty()).append(":");
            }
            if (StringUtils.isNotBlank(param.getExtendSpec())) {
                sb.append(param.getExtendSpec()).append(":");
            }
            if (StringUtils.isNotBlank(param.getNotice())) {
                sb.append(param.getNotice()).append(":");
            }
            if (null != param.getUpTime()) {
                sb.append(param.getUpTime()).append(":");
            }
            if (null != param.getDownTime()) {
                sb.append(param.getDownTime()).append(":");
            }
            if (null != param.getCompanyId()) {
                sb.append(param.getCompanyId()).append(":");
            }
            if (null != param.getPlatformId()) {
                sb.append(param.getPlatformId()).append(":");
            }
            if (null != param.getPageNumber()) {
                sb.append(param.getPageNumber()).append(":");
            }
            if (null != param.getPageSize()) {
                sb.append(param.getPageSize()).append(":");
            }
        }
        return sb.toString().substring(0, sb.toString().length() - 1);
    }

    @ApiOperation(value = "分页查询商品列表")
    @PostMapping("/listExtSpuDisplays")
    //@ApiImplicitParams({@ApiImplicitParam{name="}})
    public Response listExtSpuDisplays(@RequestBody Map<String, Object> map, HttpServletRequest rq) {

        TokenUsersVO user = UserInfoUtil.getUserInfo(rq);
        map.put("companyId", user.getCompanyId());
        map.put("platformId", user.getPlatId());
        map.put("storeId", user.getStoreId());
        return Response.data(extSpuService.listExtSpuDisplays(map));
    }

    @ApiOperation(value = "商品上架")
    @PostMapping("/extSpuShelvesUp")
    public Response extSpuShelvesUp(@RequestBody Map<String, Long> map, HttpServletRequest rq) {
        Long extId = map.get("extId");
        TokenUsersVO user = UserInfoUtil.getUserInfo(rq);
        map.put("companyId", user.getCompanyId());
        map.put("platformId", user.getPlatId());
        map.put("storeId",user.getStoreId());
        return Response.data(extSpuService.extSpuShelvesUpAndDown(extId, map, 1));
    }

    @ApiOperation(value = "商品下架")
    @PostMapping("/extSpuShelvesDown")
    public Response extSpuShelvesDown(@RequestBody Map<String, Long> map, HttpServletRequest rq) {
        Long extId = map.get("extId");
        TokenUsersVO user = UserInfoUtil.getUserInfo(rq);
        map.put("companyId", user.getCompanyId());
        map.put("platformId", user.getPlatId());
        map.put("storeId",user.getStoreId());
        return Response.data(extSpuService.extSpuShelvesUpAndDown(extId, map, 2));
    }

    @ApiOperation(value = "批量删除")
    @PostMapping("/delectByIds")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "extSpuIds", value = "ExtSpuId", required = true, dataType = "Array"),
            @ApiImplicitParam(name = "storeId", value = "店铺ID", required = true, dataType = "Long")
    })
    public Response delectByIds(@RequestBody Map<String, Object> map, HttpServletRequest rq) {

        String extSpuIdsStr = map.get("extSpuIds").toString().replace("[","").replace("]","");
        List<Long> extSpuIds = Arrays.asList(extSpuIdsStr.split(",")).stream().map(s -> Long.valueOf(s.trim())).collect(Collectors.toList());
        TokenUsersVO user = UserInfoUtil.getUserInfo(rq);
        map.put("companyId", user.getCompanyId());
        map.put("platformId", user.getPlatId());
        map.put("storeId",user.getStoreId());
        return Response.data(extSpuService.delectByIds(extSpuIds, map));
    }


    @ApiOperation(value = "根据店铺id查询扩展商品SpU")
    @GetMapping("/listByStoreId/{storeId}")
    public Response<List<ExtSpu>> listByStoreId(@PathVariable("storeId") Long storeId){
        if(null == storeId){
            return Response.failed("店铺ID不能为空");
        }
        return Response.data(extSpuService.listByStoreId(storeId));
    }


    @ApiOperation(value = "根据店铺id查询 各店铺关联对应 base_spu_id s ")
    @GetMapping("/queryStoresAndBaseSpuIds")
    public Response<Map<String, String>> queryStoresAndBaseSpuIds(@RequestParam("storeIds") List<Long> storeIds){
        if(CollectionUtils.isEmpty(storeIds)){
            return Response.failed("店铺ID集合不能为空");
        }
        storeIds.sort(null);
        return Response.data(extSpuService.queryStoresAndBaseSpuIds(storeIds, StringUtils.join(storeIds, "")));
    }

    @ApiOperation(value = "批量保存")
    @PostMapping("/saveBatch")
    public Response<Boolean> saveBatch(@RequestBody List<ExtSpu> list){
        if(CollectionUtils.isEmpty(list)){
            return Response.data(true);
        }
        return Response.data(extSpuService.saveBatch1(list));
    }


    @PostMapping("/omnipotentQuery")
    public Response omnipotentQuery(@RequestBody List<OmnipotentWrapper> wrappers) {
        return Response.data(extSpuService.omnipotentQuery(wrappers));
    }

    /**
     * 根据扩展SPU主键查找同一类扩展SPU
     * @param id 扩展SPU主键id
     * @return Response<List<ExtSpu>>
     */
    @GetMapping("/getSimilarExtSpuById/{id}")
    @ApiOperation(value = "根据扩展SPU主键查找同一类扩展SPU", notes = "根据扩展SPU主键查找同一类扩展SPU")
    public Response<List<ExtSpu>> getSimilarExtSpuById(@PathVariable("id") Long id) {
        return Response.data(extSpuService.getSimilarExtSpuById(id));
    }

    @PutMapping("/updateWeight")
    @ApiOperation(value = "权重更新")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ext_spu的id"),
            @ApiImplicitParam(name = "weight", value = "权重")
    })
    public Response updateWeight1(@RequestBody Map<String, Object> weightMap,  HttpServletRequest rq) {
        TokenUsersVO user = UserInfoUtil.getUserInfo(rq);
        weightMap.put("companyId", user.getCompanyId());
        weightMap.put("platformId", user.getPlatId());
        weightMap.put("storeId",user.getStoreId());
        return  Response.data(extSpuService.updateWeight(weightMap));
    }

    @GetMapping("/getMaxWeight")
    @ApiOperation(value = "获取某个店铺权重的最大值")
    public Response getMaxWeight(@RequestParam("storeId") Long storeId) {
        return Response.data(extSpuService.getMaxWeight(storeId));
    }

    @ApiOperation(value = "批量更新")
    @PostMapping("/updateBatch")
    public Response updateBatch(@RequestBody OmnipotentParam<ExtSpu> param) {
        return Response.data(extSpuService.updateBatch(param));
    }

}
